package com.app.lxx.pregnancyberth.ui;

import static com.app.lxx.pregnancyberth.MyApplication.modbusMaster;
import static com.app.lxx.pregnancyberth.base.UrlManage.imageUrl;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.view.animation.ScaleAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.FragmentTransaction;
import androidx.recyclerview.widget.RecyclerView;

import com.app.lxx.pregnancyberth.BuildConfig;
import com.app.lxx.pregnancyberth.Mvp.Presenter.CurrencyPresenter;
import com.app.lxx.pregnancyberth.Mvp.View.CurrencyView;
import com.app.lxx.pregnancyberth.R;
import com.app.lxx.pregnancyberth.base.ActivityManger;
import com.app.lxx.pregnancyberth.base.BaseActivity;
import com.app.lxx.pregnancyberth.base.UrlManage;
import com.app.lxx.pregnancyberth.easyphone.EasyLinphone;
import com.app.lxx.pregnancyberth.easyphone.callback.PhoneCallback;
import com.app.lxx.pregnancyberth.easyphone.callback.RegistrationCallback;
import com.app.lxx.pregnancyberth.easyphone.service.LinphoneService;
import com.app.lxx.pregnancyberth.service.BleService;
import com.app.lxx.pregnancyberth.service.DataBus;
import com.app.lxx.pregnancyberth.ui.entity.AddCallEntity;
import com.app.lxx.pregnancyberth.ui.entity.CallLogsEntity;
import com.app.lxx.pregnancyberth.ui.entity.GuangBoEntity;
import com.app.lxx.pregnancyberth.ui.entity.ScreenSetData;
import com.app.lxx.pregnancyberth.ui.entity.SmartHomeEntity;
import com.app.lxx.pregnancyberth.ui.entity.UserInfoEntity;
import com.app.lxx.pregnancyberth.ui.fragment.HospitalNotesFragement;
import com.app.lxx.pregnancyberth.ui.fragment.WardRoundFragement;
import com.app.lxx.pregnancyberth.ui.fragment.WebViewFragment;
import com.app.lxx.pregnancyberth.ui.fragment.X5WebViewFragment;
import com.app.lxx.pregnancyberth.utils.BrightnessManage;
import com.app.lxx.pregnancyberth.utils.DataToolsUtils;
import com.app.lxx.pregnancyberth.utils.NavbarUtils;
import com.app.lxx.pregnancyberth.utils.NetUtils;
import com.app.lxx.pregnancyberth.utils.TextStyleUtils;
import com.app.lxx.pregnancyberth.utils.TimeUtil;
import com.app.lxx.pregnancyberth.widge.ChineseToSpeech;
import com.app.lxx.pregnancyberth.widge.CustomerSortView;
import com.app.lxx.pregnancyberth.widge.LoadDailog.LoadDialog;
import com.app.lxx.pregnancyberth.widge.NumberSeekBar;
import com.app.lxx.pregnancyberth.widge.Ping.PingNet;
import com.app.lxx.pregnancyberth.widge.Ping.PingNetEntity;
import com.app.lxx.pregnancyberth.widge.Recycler.AutoScrollLayoutManager;
import com.app.lxx.pregnancyberth.widge.Recycler.DividerGridItemDecoration;
import com.app.lxx.pregnancyberth.widge.Recycler.MyRecycleAdapter;
import com.app.lxx.pregnancyberth.widge.UserInfo;
import com.app.lxx.pregnancyberth.widge.UtilsManage;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.Gson;
import com.squareup.picasso.Picasso;
import com.sunfusheng.marqueeview.MarqueeView;
import com.youth.banner.Banner;
import com.youth.banner.listener.OnBannerListener;
import com.youth.banner.loader.ImageLoader;
import com.zjy.portdemo.ColorPickerView;

import org.json.JSONException;
import org.json.JSONObject;
import org.linphone.core.LinphoneCall;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * Created by Lxx on PregnancyBerth
 * 2019/8/26 11:25 星期三
 * Details：首页 APP首页
 */
public class VoipP2PActivity extends BaseActivity<CurrencyPresenter> implements CurrencyView, View.OnClickListener {
    private static final String TAG = "VoipP2PActivity";
    // 第一次按下返回键的事件
    private long firstPressedTime = 0;
    private int clickNum = 0;
    private boolean isBusy = false;  //是否正在通话中。true 表示正忙 false 表示为不忙。
    //private boolean isAnswer = false;  //是否正在通话中。true 表示正忙 false 表示为不忙。
    private boolean isCallPhone = false;

    View main_cardv;

    Handler timeHandler = new Handler();

    private View four_myalbum, four_ebook, four_phoneCall, four_mind, root_view, user_input_view, calling_view;

    private CustomerSortView btn_main, btn_zyxz, btn_fycx, btn_yzcx, btn_cfjl, btn_baby, btn_more;
    private HospitalNotesFragement hospitalNotesFragement;
    private WebViewFragment webViewFragment;
    private ImageView dianxin;
    private String msg = "";
    private ImageView enter_manage;
    private LinearLayout cfStartbg;
    private TextView cfName, cfInfo, cfTime, cfZyid, cfPhry, cfStart, appStart, cfZrys, cfZbys, cfZrhs,
            cfZbhs, cfZchs, cfXbmr, cfCsrq, cfDianzan, targetidText;
    private ArrayList<UserInfoEntity.DataBean.MaternalBean.ShowItemsBean> showItemsBeans = new ArrayList<>();
    private MyRecycleAdapter<UserInfoEntity.DataBean.MaternalBean.ShowItemsBean> myAdapterInfo;
    private CountDownTimer downTimer;
    private WardRoundFragement wardRoundFragement;
    private LinearLayout controlView;
    private Banner banner;
    private MyRecycleAdapter<String> myRecycleAdapterZysx;
    private ArrayList<String> arrayListZysx = new ArrayList<>();
    private RecyclerView myRecyclerInfo;
    private TextView messageTitle;
    private ImageView advertisement;
    private ImageView message_iv;

    private boolean isHaveBroadcast = false;
    private X5WebViewFragment x5WebViewFragment;
    private MediaPlayer mediaPlayer;

    private View mHangUp, mCallIn, mToggleSpeaker, mToggleMute;
    private String xibaoID;
    private String zan = "0";
    private String email = "";

    private List<SmartHomeEntity.DataBean.IntelligentDataBean> intelligentDataBeanList = new ArrayList<>();
    private boolean networkState;
    private boolean pingResult;
    private RecyclerView myRecyclerViewZYSX;

    String phoneNumber = "";

    private long refreshTime = 1000 * 60 * 3;
    private SmartHomeEntity smartHomeEntity;
    private RecyclerView myRecyclerZnjj;
    private MyRecycleAdapter<SmartHomeEntity.DataBean.IntelligentDataBean> myRecycleAdapterZn;
    private int address;
    private int anInt;
    private boolean isHavePeople = true;
    private View view_front_black;
    private ChineseToSpeech chineseToSpeech;
    private String callingLogId = "";
    private final int index_change_call_status = 14;
    //    private final int index_check_call_status = 12;
    final static int type_load_calllogs = 13;
    private UserInfoEntity.DataBean maternalData;
    private View view_clack_black;
    private View iv_logo;
    private boolean isUpDateStatus = true;//是否需要更新通话状态
    private boolean inComingCall = false;
    private ScreenSetData mScreenSetData;
    private View btn_clock;
    private View btn_closeScreen;
    private TextView cfInfo2;


    //跳转activity
    public static void newInstance(Context context) {
        try {
            ActivityUtils.finishAllActivities();
        } catch (Exception e) {
            e.printStackTrace();
        }
        context.startActivity(new Intent(context, VoipP2PActivity.class));
    }

    @Override
    protected CurrencyPresenter createP() {
        return new CurrencyPresenter();
    }

    private void initView() {
        view_front_black = findViewById(R.id.view_front_black);
        view_clack_black = findViewById(R.id.view_clack_black);
        btn_main = findViewById(R.id.btn_main);
        btn_zyxz = findViewById(R.id.btn_zyxz);
        btn_fycx = findViewById(R.id.btn_fycx);
        btn_yzcx = findViewById(R.id.btn_yzcx);
        btn_cfjl = findViewById(R.id.btn_cfjl);
        btn_baby = findViewById(R.id.btn_baby);
        btn_more = findViewById(R.id.btn_more);
        btn_clock = findViewById(R.id.btn_clock);
        btn_closeScreen = findViewById(R.id.btn_closeScreen);
        iv_logo = findViewById(R.id.iv_logo);

        main_cardv = findViewById(R.id.main_cardv);
        user_input_view = findViewById(R.id.user_input_view);
        calling_view = findViewById(R.id.calling_view);

        four_myalbum = findViewById(R.id.four_myalbum);
        four_ebook = findViewById(R.id.four_ebook);
        four_phoneCall = findViewById(R.id.four_phoneCall);
        four_mind = findViewById(R.id.four_mind);

        root_view = findViewById(R.id.root_view);

        messageTitle = findViewById(R.id.message_title);
        message_iv = findViewById(R.id.message_iv);
        controlView = findViewById(R.id.intelligentControl_view);
        enter_manage = findViewById(R.id.enter_manage);

        advertisement = findViewById(R.id.advertisement);
        banner = findViewById(R.id.banner);

        dianxin = findViewById(R.id.dianxin);
        cfStartbg = findViewById(R.id.cf_startbg);
        cfName = findViewById(R.id.cf_name);
        cfInfo = findViewById(R.id.cf_info);
        cfInfo2 = findViewById(R.id.cf_info2);
        cfTime = findViewById(R.id.cf_time);
        cfZyid = findViewById(R.id.cf_zyid);
        cfPhry = findViewById(R.id.cf_phry);
        cfStart = findViewById(R.id.cf_start);
        appStart = findViewById(R.id.app_start);
        cfZrys = findViewById(R.id.cf_zrys);
        cfZbys = findViewById(R.id.cf_zbys);
        cfZrhs = findViewById(R.id.cf_zrhs);
        cfZbhs = findViewById(R.id.cf_zbhs);
        cfZchs = findViewById(R.id.cf_zchs);
        cfXbmr = findViewById(R.id.cf_xbmr);
        cfCsrq = findViewById(R.id.cf_csrq);
        cfDianzan = findViewById(R.id.cf_dianzan);

        targetidText = findViewById(R.id.targetid_text);
        mHangUp = findViewById(R.id.hang_up);
        mCallIn = findViewById(R.id.accept_call);
        mToggleSpeaker = findViewById(R.id.toggle_speaker);
        mToggleMute = findViewById(R.id.toggle_mute);


        btn_main.setOnClickListener(this);
        btn_zyxz.setOnClickListener(this);
        btn_fycx.setOnClickListener(this);
        btn_yzcx.setOnClickListener(this);
        btn_cfjl.setOnClickListener(this);
        btn_baby.setOnClickListener(this);
        btn_more.setOnClickListener(this);
        iv_logo.setOnClickListener(this);
        btn_clock.setOnClickListener(this);
        btn_closeScreen.setOnClickListener(this);

        four_myalbum.setOnClickListener(this);
        four_ebook.setOnClickListener(this);
        four_phoneCall.setOnClickListener(this);
        four_mind.setOnClickListener(this);
        //息屏遮罩层点击事件
        view_front_black.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                view_front_black.setVisibility(View.GONE);
                setDelayTimeToScreen();
            }
        });
        //设置挂断按钮
        mHangUp.setOnClickListener(this);
        mCallIn.setOnClickListener(this);

        advertisement.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                ToastUtils.showShort("测试");

            }
        });
        if (BuildConfig.DEBUG) {
            cfInfo.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ToastUtils.showShort("子线程触发");
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            DataBus.post("callButton", new DataBus.Message(1));
                        }
                    }).start();
                }
            });
            cfName.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ToastUtils.showShort("主线程触发");
                    DataBus.post("callButton", new DataBus.Message(1));
                }
            });
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        LogUtils.e("onNewIntent");
        resumeWork();
    }
    private void initSubcribes() {
        DataBus.unSubscribe("callButton");
        DataBus.unSubscribe("netChanged");
        Log.e("sssssButtonService", "VoipP2PActivity initSubcribes");


        DataBus.subscribe("callButton", new DataBus.Subscriber() {
            @Override
            protected void onReceive(DataBus.Message msg) {
                try {
                    Log.e("sssssButtonService", "VoipP2PActivity onReceive msg="+msg);
                    if (msg.what == 1) {//手柄监听，release版本下才能启用
                        Log.e("sssssButtonService", "VoipP2PActivity CallPhoneIntent");
                        Log.e("sssssButtonServicemsg=1", String.format("isCallPhone:%s,isBusy:%s,isAnswer:%s", isCallPhone, isBusy, "isAnswer"));
                        if (view_clack_black.getVisibility()==View.VISIBLE){
                            view_clack_black.setVisibility(View.GONE);
                            setBtnClick(btn_main);
                        }
                        if (view_front_black.getVisibility()==View.VISIBLE){
                            view_front_black.setVisibility(View.GONE);
                            setBtnClick(btn_main);
                        }
                        if (main_cardv.getVisibility()==View.VISIBLE){
                            main_cardv.setVisibility(View.GONE);
                            setBtnClick(btn_main);
                        }

                        if (System.currentTimeMillis() - firstPressedTime > 100) {//设置按钮重复按在1秒间隔
                            if (isCallPhone) {
                                if (isBusy) {
                                    // 挂断
                                    user_input_view.setVisibility(View.VISIBLE);
                                    calling_view.setVisibility(View.GONE);
                                    hangUp();
                                    isCallPhone = false;
                                    isBusy = false;
                                } else {
                                    // 接听
                                    mCallIn.setVisibility(View.GONE);
                                    calling_view.setVisibility(View.VISIBLE);
                                    acceptCall();
                                    isBusy = true;
                                }
                            } else {
                                try {
                                    audioCall(phoneNumber);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                    showToast(e.getMessage());
                                }
                            }
                        } else {
                            firstPressedTime = System.currentTimeMillis();
                        }
                        view_front_black.setVisibility(View.GONE);
                        setDelayTimeToScreen();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        DataBus.subscribe("netChanged", new DataBus.Subscriber() {
            @Override
            protected void onReceive(DataBus.Message msg) {
                try {
                    boolean isConnected = NetUtils.isNetworkConnected(context);
                    Log.e("NetReceiver", "网络状态：" + isConnected);
                    Log.e("NetReceiver", "网络连接类型：" + NetUtils.getConnectedType(context));
                    if (isConnected) {
                        try {
                            EasyLinphone.login();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } else {

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void setDelayTimeToScreen() {
        try {
            long blackScreenTime = 30;//暂定单位为分钟
            if (mScreenSetData != null) {
                blackScreenTime = Long.parseLong(mScreenSetData.getData().getJg_time());
            }
            blackScreenTime = 1;//todo test
            blackScreenTime = System.currentTimeMillis() + blackScreenTime * 60 * 1000;
            view_front_black.setTag(blackScreenTime);
            LogUtils.e("current:" + TimeUtils.millis2String(System.currentTimeMillis()),
                    "close:" + TimeUtils.millis2String(blackScreenTime));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

//    public static String CallPhoneIntent = "com.action.callphoneServicce";
//    public static String NETWORKCHANGE = "com.action.NETWORKCHANGE";



    @Override
    protected void initBindViewId() {
        chineseToSpeech = new ChineseToSpeech(context);
        //检查写入权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
            //拥有读写文件权限
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { //版本在23及以上
                if (!Settings.System.canWrite(this)) { //是否有Settings写入权限
                    // 以下是请求写入系统设置权限逻辑
                    new AlertDialog.Builder(this).setTitle("授权申请").setMessage("请允许系统设置写入权限").setPositiveButton("去设置", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Intent intent = new Intent(android.provider.Settings.ACTION_MANAGE_WRITE_SETTINGS);
                            intent.setData(Uri.parse("package:" + getPackageName()));
                            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); //开启一个新activity
                            startActivity(intent);
                            showToast("请允许系统设置写入权限");
                        }
                    }).setCancelable(false).show();
                } else {
                    //有了权限，具体的动作

                }
            }
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION,
                        Manifest.permission.ACCESS_LOCATION_EXTRA_COMMANDS}, 140);
            }
        } else {
            //没有读写权限
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.READ_EXTERNAL_STORAGE}, 140);
            }
        }


        initView();

        enter_manage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (System.currentTimeMillis() - firstPressedTime < 1500) {
                    clickNum++;
                    Log.e("进入管理模式", "管理模式" + clickNum);
                    if (clickNum >= 3) {
                        Log.e("进入管理模式", "进入管理模式" + clickNum);
                        Intent intent = new Intent(getApplicationContext(), ControllerActivity.class);
                        intent.putExtra("manageMode", true);
                        startActivity(intent);
                    }
                } else {
                    clickNum = 0;
                    firstPressedTime = System.currentTimeMillis();
                }
            }
        });

        String bindNurseAccount = shareference.getBindNurseUser();
        if (!TextUtils.isEmpty(bindNurseAccount)) {
            phoneNumber = bindNurseAccount;
        } else {
            showToast("未绑定护士账号");
        }

        initRecyclerView();
        initRecyclerViewZnjj();
        initLinPhoneCall();

        RequestOptions requestOptions = new RequestOptions();
        requestOptions.error(R.drawable.iv_advertisement).placeholder(R.drawable.iv_advertisement);
        Glide.with(this).load(R.drawable.iv_advertisement)
                .apply(requestOptions).into(advertisement);

        dianxin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!shareference.getXiBaoDataZt(xibaoID)) {
                    anim(v);
                    dianxin.setImageDrawable(getResources().getDrawable(R.drawable.iv_dianxin_y));
                    submitZan();
                } else {
                    showToast("已点过赞");
                }
            }
        });


        findViewById(R.id.intelligent_out).
                setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        controlView.setVisibility(View.GONE);
                        root_view.setVisibility(View.VISIBLE);
                    }
                });

        mediaPlayer = new MediaPlayer();


        // showToast("" + isCallPhone);
        NavbarUtils.hideBottomUIMenu(this);

        startService(new Intent(context, BleService.class).putExtra("startSearch", true));
    }

    private void startLoadData() {
        downTimer = new CountDownTimer(refreshTime, 1000) {
            public void onTick(long millisUntilFinished) {
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm:ss");// HH:mm:ss
                // 获取当前时间
                Date date = new Date(System.currentTimeMillis());
                String format = simpleDateFormat.format(date);
                //Log.e("CountDownTimer", "CountDownTimer==>" + format);
                if (!isCallPhone) {
                    if (format.equals("02:50:00")) {
                        restartApp();
                    }
                    if (millisUntilFinished / 1000 % 20 == 0) {//20秒执行一次
                        autoCloseScreen();
                        checkPhoneContion();
                    }
                }
            }

            public void onFinish() {
                downTimer.start();
                if (!isHaveBroadcast) {
                    loadData();
                }
            }
        };

        downTimer.start();
    }

    private void checkPhoneContion() {
//        EasyLinphone.getLC().;
    }

    private void autoCloseScreen() {
        //{"close_time":"21:00:00","open_time":"08:00:00","jg_time":"25"}}
        int openHour = 8;
        int openMin = 0;
        int closeHour = 21;
        int closeMin = 0;
        if (mScreenSetData != null) {
            String openTime = mScreenSetData.getData().getOpen_time();
            String closeTime = mScreenSetData.getData().getClose_time();
            Date dateOpen = TimeUtils.string2Date(openTime, new SimpleDateFormat("HH:mm:ss"));
            Date dateClose = TimeUtils.string2Date(closeTime, new SimpleDateFormat("HH:mm:ss"));
            Calendar cNow = Calendar.getInstance();
            cNow.setTime(dateOpen);

            openHour = cNow.get(Calendar.HOUR_OF_DAY);
            openMin = cNow.get(Calendar.MINUTE);
            cNow = Calendar.getInstance();
            cNow.setTime(dateClose);
            closeHour = cNow.get(Calendar.HOUR_OF_DAY);
            closeMin = cNow.get(Calendar.MINUTE);

            LogUtils.e("openstr:" + openTime);
            LogUtils.e("open:" + TimeUtils.date2String(dateOpen));
            LogUtils.e("closestr:" + closeTime);
            LogUtils.e("close:" + TimeUtils.date2String(dateClose));
        }
        LogUtils.e("openHour "+openHour,
                "openMin "+openMin,
                "closeHour "+closeHour,
                "closeMin "+closeMin);
        if (BrightnessManage.isCurrentInTimeScope(openHour, openMin, closeHour, closeMin)) {

//                        showToast("正常时间");
            LogUtils.e("自动亮屏");
            view_front_black.setVisibility(View.GONE);
            view_front_black.setTag(0);
        } else {
            try {
                long closeT = (long) view_front_black.getTag();
                if (System.currentTimeMillis() < closeT) {
                    LogUtils.e("不到息屏时间");
                    return;
                }
            } catch (Exception e) {
//                e.printStackTrace();
            }
            LogUtils.e("自动息屏");
            view_front_black.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        setDelayTimeToScreen();
        return super.dispatchTouchEvent(ev);
    }

    private void loadData() {
        requestImfoIndex();
        requestGuangboIndex();
        requestDoctor();
        checkNetworkStatus();
        loadScreenset();
    }

    final int index_load_screen_set = 0x315;

    private void loadScreenset() {
        HashMap<String, String> map = new HashMap<>();
        getP().requestGet(index_load_screen_set, UrlManage.APP_URL + "index/screenset", map);
    }

    // 重启应用
    @SuppressLint("WrongConstant")
    public void restartApp() {
        try {
            Intent intent = new Intent();
            // 参数1：包名，参数2：程序入口的activity
            intent.setClassName(getPackageName(), "com.app.lxx.pregnancyberth.ui.MainActivity");
            PendingIntent restartIntent = PendingIntent.getActivity(
                    getApplicationContext(), 0, intent,
                    Intent.FLAG_ACTIVITY_NEW_TASK);
            AlarmManager mgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
            mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 1000, restartIntent); // 1秒钟后重启应用

            ActivityManger.finshApp();
            android.os.Process.killProcess(android.os.Process.myPid());
            System.exit(10);
        } catch (Exception e) {

        }

    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        try {
            if (requestCode == 140) {
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                } else {
                    showToast("未授予权限");
                    System.exit(0);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private void checkNetworkStatus() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                networkState = NetUtils.isNetworkConnected(context);
                PingNetEntity pingNetEntity = new PingNetEntity(shareference.getServiceIp(), 3, 5, new StringBuffer());
                pingNetEntity = PingNet.ping(pingNetEntity);
                pingResult = pingNetEntity.isResult();

                timeHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        StringBuilder stringBuilder = new StringBuilder();
                        if (networkState) {
                            stringBuilder.append("网络在线  ");
                        } else {
                            stringBuilder.append("网络异常  ");
                        }
                        if (pingResult) {
                            stringBuilder.append("服务器在线");
                        } else {
                            stringBuilder.append("服务器异常");
                        }
                        appStart.setText(stringBuilder.toString());
                    }
                });
            }
        }).start();
    }

    @Override
    protected boolean hidetitle() {
        return true;
    }

    @Override
    protected String settitle() {
        return "首页";
    }

    @NonNull
    @Override
    public int setxmlview() {
        return R.layout.activity_voip_p2p;
    }

    private void anim(View v) {
        ScaleAnimation scaleAnimation = (ScaleAnimation) AnimationUtils.loadAnimation(this, R.anim.anim_scale);
        v.startAnimation(scaleAnimation);
    }

    @Override
    protected void onResume() {
        super.onResume();
        LogUtils.e("onResume");
        resumeWork();
        initLinPhoneCall();
    }

    private void resumeWork() {
        Log.e("sssssButtonService", "VoipP2PActivity resumeWork");
        loadData();
        startLoadData();
        if (getSp("clock").getBoolean("showclock", false)) {
            view_clack_black.setVisibility(View.VISIBLE);
        } else {
            view_clack_black.setVisibility(View.GONE);
        }
        isBusy = false;  //是否正在通话中。true 表示正忙 false 表示为不忙。
        //private boolean isAnswer = false;  //是否正在通话中。true 表示正忙 false 表示为不忙。
        isCallPhone = false;
        initSubcribes();
        Log.e("sssssButtonService", "VoipP2PActivity resumeWork end");
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (downTimer != null) {
            downTimer.cancel();
        }
    }

    //点击后退键触发的方法
    @Override
    public void onBackPressed() {
//        new AlertDialog.Builder(VoipP2PActivity.this).setCancelable(true)
//                .setTitle("是否退出?")
//                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface arg0, int arg1) {
//                    }
//                }).setPositiveButton("确定", new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface arg0, int arg1) {
//                        finish(); //确定以后调用退出方法
//                    }
//                }
//        ).show();
        ToastUtils.showShort("不支持退出");
        //super.onBackPressed();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopMusic();
        chineseToSpeech.destroy();
        stopService(new Intent(context, BleService.class));
    }


    //记录点击事件
    private CustomerSortView clickView;

    int localTag=1;//标识当前所选界面，从左到右，1，2，3，4，5；
    //设置点击事件
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_main:
                initLinPhoneCall();
                downTimer.start();
                setBtnClick(btn_main);
                localTag=1;
                break;
            case R.id.btn_zyxz:
                initLinPhoneCall();
                downTimer.cancel();
                setBtnClick(btn_zyxz);
                localTag=2;
                break;
            case R.id.btn_fycx:
                Toast.makeText(this, "暂未开放", Toast.LENGTH_SHORT).show();
                break;
            case R.id.btn_yzcx:
                Toast.makeText(this, "暂未开放", Toast.LENGTH_SHORT).show();
                break;
            case R.id.btn_cfjl:
                initLinPhoneCall();
                downTimer.cancel();
                setBtnClick(btn_cfjl);
                localTag=3;
                break;
            case R.id.btn_baby:
                initLinPhoneCall();
                downTimer.cancel();
                setBtnClick(btn_baby);
                localTag=4;
                break;
            case R.id.btn_clock:
                initLinPhoneCall();
                view_clack_black.setVisibility(View.VISIBLE);
                getSp("clock").edit().putBoolean("showclock", true).apply();
                localTag=5;
                break;
            case R.id.btn_closeScreen:
                initLinPhoneCall();
                //息屏
                view_front_black.setVisibility(View.VISIBLE);
                view_front_black.setTag(0);
                localTag=6;
                break;
            case R.id.btn_more:
                //Toast.makeText(this, "暂未开放", Toast.LENGTH_SHORT).show();

                new AlertDialog.Builder(this).setTitle("更多应用").setItems(new String[]{"时钟", "息屏", "取消"}, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        switch (which) {
                            case 0:
                                view_clack_black.setVisibility(View.VISIBLE);
                                getSp("clock").edit().putBoolean("showclock", true).apply();
                                break;
                            case 1:
                                //息屏
                                view_front_black.setVisibility(View.VISIBLE);
                                view_front_black.setTag(0);
                                break;
                            case 2:
                                dialog.dismiss();
                                break;
                        }
                    }
                }).show();
                break;

            /************************/
            case R.id.four_myalbum:
                Bundle bundle=new Bundle();
                bundle.putString("email",email);
                bundle.putString("callingLogId",callingLogId);
                startActivity(new Intent(this, MyAlbumActivity.class).putExtras(bundle));
                break;
            case R.id.four_ebook:
                startActivity(new Intent(this, MyEbookActivity.class));
                break;
            case R.id.four_phoneCall:
                try {
                    audioCall(phoneNumber);
                } catch (Exception e) {
                    e.printStackTrace();
                    showToast(e.getMessage());
                }
                break;
            case R.id.four_mind:
                root_view.setVisibility(View.GONE);
                controlView.setVisibility(View.VISIBLE);
                requestBedinfo();
                break;
            /********************/

            case R.id.accept_call:
                // 接听
                mCallIn.setVisibility(View.GONE);
                acceptCall();
                break;
            case R.id.hang_up:
                // 挂断
                user_input_view.setVisibility(View.VISIBLE);
                calling_view.setVisibility(View.GONE);
                hangUp();
                break;
            case R.id.iv_logo:
                view_clack_black.setVisibility(View.GONE);
                getSp("clock").edit().putBoolean("showclock", false).apply();
                break;
        }
    }

    private SharedPreferences getSp(String name) {
        return getSharedPreferences(name, Context.MODE_PRIVATE);
    }

    private void initRecyclerView() {
        UtilsManage utilsManage = new UtilsManage(this);
        //注意事项
        myRecyclerViewZYSX = findViewById(R.id.myRecyclerView);
        myRecycleAdapterZysx = new MyRecycleAdapter<String>(context,
                arrayListZysx, R.layout.item_userknow_layout, false) {
            @Override
            protected void setPositionClick(int position) {

            }

            @Override
            protected void initData(MyViewHolder holder, int position) {
                holder.setText(R.id.userknow_tv, arrayListZysx.get(position));
            }
        };

        // myRecyclerView.setLayoutManager(new FlowLayoutManager());
        myRecyclerViewZYSX.setLayoutManager(new AutoScrollLayoutManager(context));
        // myRecyclerViewZYSX.setLayoutManager(utilsManage.linearLayoutManager(context, LinearLayout.VERTICAL, true));
        myRecyclerViewZYSX.setAdapter(myRecycleAdapterZysx);

        myRecyclerViewZYSX.setOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                // 如果自动滑动到最后一个位置，则此处状态为SCROLL_STATE_IDLE
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    AutoScrollLayoutManager lm = (AutoScrollLayoutManager) recyclerView
                            .getLayoutManager();
                    int position = lm.findLastCompletelyVisibleItemPosition();
                    int count = lm.getItemCount();
                    if (position == count - 1) {
                        lm.scrollToPosition(0);
                        myRecyclerViewZYSX.smoothScrollToPosition(myRecycleAdapterZysx.getItemCount());
                    }
                }
            }
        });


        //信息
        myRecyclerInfo = findViewById(R.id.myRecyclerInfo);
        myAdapterInfo = new MyRecycleAdapter<UserInfoEntity.DataBean.MaternalBean.ShowItemsBean>(context,
                showItemsBeans, R.layout.item_userinfo_lb_layout, false) {
            @Override
            protected void setPositionClick(int position) {

            }

            @Override
            protected void initData(MyViewHolder holder, int position) {
                UserInfoEntity.DataBean.MaternalBean.ShowItemsBean showItemsBean = showItemsBeans.get(position);
                // List<String> keys = new ArrayList<>(stringStringHashMap.keySet());
                //  Gson gson = new Gson();
                //  Type type = new TypeToken<List<User>>() {
                //  }.getType();
                //  List<User> list = gson.fromJson(responseData, type);
                String title = showItemsBean.getTitle();
                if (title.length() > 6) {
                    holder.setText(R.id.userinfo_title, title.substring(0, 6) + "：");
                } else {
                    holder.setText(R.id.userinfo_title, title + "：");
                }

                MarqueeView marqueeView = holder.getView(R.id.marqueeView);

                if (position != 5) {
                    holder.setText(R.id.withText, showItemsBean.getValue());
                    marqueeView.setVisibility(View.INVISIBLE);
                    holder.setVisibile(R.id.withText, true);
                } else {
                    holder.setVisibile(R.id.withText, false);
                    marqueeView.setVisibility(View.VISIBLE);
                    marqueeView.stopFlipping();
                    marqueeView.startWithText(showItemsBean.getValue());
                }

                View userinfoly = holder.getView(R.id.userinfoly);
                try {
                    String color = showItemsBean.getSetting();
                    if (!TextUtils.isEmpty(color)) {
                        String extend = "#" + color;
                        userinfoly.setBackgroundColor(Color.parseColor(extend));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    userinfoly.setBackgroundColor(Color.parseColor("#ffffff"));
                }
            }
        };

        myRecyclerInfo.setLayoutManager(utilsManage.linearLayoutManager(context, LinearLayout.VERTICAL, true));
        myRecyclerInfo.addItemDecoration(new DividerGridItemDecoration(context,
                DividerGridItemDecoration.HORIZONTAL_LIST, 2,
                Color.parseColor("#00FFFFFF")));
        myRecyclerInfo.setAdapter(myAdapterInfo);
    }

    List<GuangBoEntity.DataBean> boEntitys = new ArrayList<>();

    private void startMusic(int index) {
        if (mediaPlayer != null && mediaPlayer.isPlaying()) {
            mediaPlayer.release();
            mediaPlayer = new MediaPlayer();
        }
        try {
            GuangBoEntity.DataBean dataBean = boEntitys.get(index);
            String musicUrl = imageUrl + dataBean.getVideofile();
            arrayListZysx.clear();
            arrayListZysx.add(dataBean.getContent());
            myRecycleAdapterZysx.notifyDataSetChanged();
            message_iv.setVisibility(View.VISIBLE);
            //  String musicUrl = "https://m10.music.126.net/20190816103611/cf5fec7a980ab69c3ae9072d168b7258/ymusic/0453/5552/540e/393c72c247b829bf7d28cd2386a409b6.mp3";
            if (TextUtils.isEmpty(musicUrl)) {
                musicUrl = "http://www.ytmp3.cn/down/57799.mp3";
            }
            //设置播放的数据源。
            Log.e("musicUrl", musicUrl);
            mediaPlayer.setDataSource(musicUrl);
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mediaPlayer.prepareAsync();//异步的准备
            mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    mediaPlayer.start();
                    int max = mediaPlayer.getDuration();
                    Log.i("mediaplayer", max + "最大");
                }
            });
            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    int index2 = index + 1;
                    if (index2 < boEntitys.size()) {
                        startMusic(index2);
                    } else {
                        requestImfoIndex();
                        timeHandler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                message_iv.setVisibility(View.INVISIBLE);
                                messageTitle.setText(getString(R.string.pointsAttention));
                                isHaveBroadcast = false;
                                Log.e("mediaplayer", "时间到 isHaveBroadcast = " + isHaveBroadcast);
                            }
                        }, refreshTime);
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            requestImfoIndex();
            timeHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    message_iv.setVisibility(View.INVISIBLE);
                    messageTitle.setText(getString(R.string.pointsAttention));
                    isHaveBroadcast = false;
                    Log.e("mediaplayer", "时间到 isHaveBroadcast = " + isHaveBroadcast);
                }
            }, refreshTime);
        }
    }

    public void stopMusic() {
        if (mediaPlayer != null && mediaPlayer.isPlaying()) {
            mediaPlayer.stop();
            mediaPlayer.release();
            mediaPlayer = null;
        }
    }


    // 智能家居控制
    private void initRecyclerViewZnjj() {
        //信息
        myRecyclerZnjj = findViewById(R.id.myRecyclerZnjj);
        initRyZnjjAdapter();
//        smartHomeAdapter = new SmartHomeAdapter(this, intelligentDataBeanList);
        myRecyclerZnjj.setLayoutManager(utilsManage.linearLayoutManager(context, LinearLayout.VERTICAL, true));
        myRecyclerZnjj.addItemDecoration(new DividerGridItemDecoration(context,
                DividerGridItemDecoration.HORIZONTAL_LIST, 12,
                Color.parseColor("#00FFFFFF")));
        myRecyclerZnjj.setAdapter(myRecycleAdapterZn);
//        smartHomeAdapter.setOnClickListener(new SmartHomeAdapter.OnClickItemListener() {
//            @Override
//            public void onClickListener(int position) {
//
//                //   Intent intent = new Intent(VoipP2PActivity.this, LightingActivity.class);
//                //   intent.putExtra("position", position);
//                //   intent.putExtra("SmartHomeEntity", smartHomeEntity);
//                //   startActivity(intent);
//
//                //  showColorPickerView();
//
//            }
//        });
    }


    private void setBtnClick(CustomerSortView view) {

        btn_main.setColor(R.color.transparent);
        btn_zyxz.setColor(R.color.transparent);
        btn_fycx.setColor(R.color.transparent);
        btn_yzcx.setColor(R.color.transparent);
        btn_cfjl.setColor(R.color.transparent);
        btn_baby.setColor(R.color.transparent);
        btn_more.setColor(R.color.transparent);

        view.setColor(R.color.white);

        if (view == btn_main) {
            main_cardv.setVisibility(View.GONE);
        } else {
            main_cardv.setVisibility(View.VISIBLE);
        }

        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        hideFragments(fragmentTransaction);

        if (clickView != view) {
            switch (view.getId()) {
                case R.id.btn_zyxz:
                    if (hospitalNotesFragement == null) {
                        hospitalNotesFragement = new HospitalNotesFragement();
                        fragmentTransaction.add(R.id.main_fragment, hospitalNotesFragement);
                    } else {
                        fragmentTransaction.remove(hospitalNotesFragement);
                        hospitalNotesFragement = new HospitalNotesFragement();
                        fragmentTransaction.add(R.id.main_fragment, hospitalNotesFragement);
                    }
                    break;
                case R.id.btn_cfjl:
                    if (wardRoundFragement == null) {
                        wardRoundFragement = new WardRoundFragement();
                        fragmentTransaction.add(R.id.main_fragment, wardRoundFragement);
                    } else {
                        fragmentTransaction.remove(wardRoundFragement);
                        wardRoundFragement = new WardRoundFragement();
                        fragmentTransaction.add(R.id.main_fragment, wardRoundFragement);
                    }
                    break;
                case R.id.btn_baby:
                    String babyID = shareference.getUserID();
                    //baobao_ziliao/index.html?id=22
                    msg = urlManage.imageUrl + "/baobao_ziliao/index.html?id=" + babyID + "&baby_id=" + babyID;
                    Log.e("baby", msg);
                    if (x5WebViewFragment == null) {
                        x5WebViewFragment = new X5WebViewFragment();
                        Bundle bundle = new Bundle();
                        bundle.putString("BABYURL", msg);
                        x5WebViewFragment.setArguments(bundle);
                        fragmentTransaction.add(R.id.main_fragment, x5WebViewFragment);
                    } else {
                        fragmentTransaction.remove(x5WebViewFragment);
                        x5WebViewFragment = new X5WebViewFragment();
                        Bundle bundle = new Bundle();
                        bundle.putString("BABYURL", msg);
                        x5WebViewFragment.setArguments(bundle);
                        fragmentTransaction.add(R.id.main_fragment, x5WebViewFragment);
                    }
                    break;
            }
            fragmentTransaction.commit();
        }

        clickView = view;
    }

    private void hideFragments(FragmentTransaction transaction) {
        if (hospitalNotesFragement != null) {
            transaction.hide(hospitalNotesFragement);
        }
        if (x5WebViewFragment != null) {
            transaction.hide(x5WebViewFragment);
        }
        if (wardRoundFragement != null) {
            transaction.hide(wardRoundFragement);
        }
    }

    public String transmitData() {
        return msg;
    }

    @Override
    public void requestCurrencyView(int type, String body) {
        try {
            switch (type) {
                case index_load_screen_set:
                    mScreenSetData = new Gson().fromJson(body, ScreenSetData.class);

                    break;
                case type_load_calllogs:

                    Log.d("ddd", body);
                    CallLogsEntity logEntitys = new Gson().fromJson(body, CallLogsEntity.class);
                    if (logEntitys.getCode() == 1) {
                        List<CallLogsEntity.DataBean> logs = logEntitys.getData();
                        for (CallLogsEntity.DataBean log : logs) {
                            String callstatus = log.getCall_status();
                            String id = log.getId();
                            if ("2".equals(callstatus)) {
                                if (shareference.getLinPhonDataZh().equals(log.getTo())) {
                                    callingLogId = id;
                                    Log.d("call", "找到id:" + callingLogId);
//                                    checkCallingStatus();
                                    stopLoadCallLogTimer();
                                    return;
                                }
                            }
                        }
                    }
                    startLoadCallLogTimer();
                    break;

                case index_addcalllog:
                    AddCallEntity callEntity = new Gson().fromJson(body, AddCallEntity.class);
                    String data_id = callEntity.getData();
                    if (!TextUtils.isEmpty(data_id)) {
                        callingLogId = data_id;
                    }
                    Log.e("call", "callId:" + callingLogId);
                    break;
            }


            if (!isCallPhone) {//未通话状态 ...不知道为啥要这样判断
                switch (type) {
                    case index_index:
                        UserInfoEntity userInfoEntity = new Gson().fromJson(body, UserInfoEntity.class);
                        UserInfoEntity.DataBean data = userInfoEntity.getData();

                        if (data != null) {
                            maternalData = userInfoEntity.getData();
                            UserInfoEntity.DataBean.MaternalBean maternal = data.getMaternal();
                            email = maternal.getEmail();
                            String id = maternal.getId();
                            shareference.saveUserID(id);
                            String avatar = maternal.getAvatar();
                            if (!TextUtils.isEmpty(avatar)) {
                                Picasso.with(context).load(imageUrl + avatar).placeholder(R.drawable.iv_tx).error(R.drawable.iv_tx).into(enter_manage);
                            }
                            String cate = maternal.getCate();
                            if (!TextUtils.isEmpty(cate)) {
                                if (cate.equals("1")) {
                                    cfStartbg.setBackgroundResource(R.color.green);
                                    cfStart.setTextColor(getResources().getColor(R.color.green));
                                } else if (cate.equals("2")) {
                                    cfStartbg.setBackgroundResource(R.color.orange);
                                    cfStart.setTextColor(getResources().getColor(R.color.orange));
                                } else if (cate.equals("3")) {
                                    cfStartbg.setBackgroundResource(R.color.red);
                                    cfStart.setTextColor(getResources().getColor(R.color.red));
                                }
                            }

                            String dc_state = maternal.getDc_state();
                            if (!TextUtils.isEmpty(dc_state)) {
                                if (dc_state.equals("1")) {
                                    cfStart.setText("待产中");
                                    UserInfo.UserType = "待产中";
                                } else if (dc_state.equals("2")) {
                                    cfStart.setText("生产中");
                                    UserInfo.UserType = "生产中";
                                } else if (dc_state.equals("3")) {
                                    cfStart.setText("产后 " + maternal.getSc_days() + "天");
                                    UserInfo.UserType = "产后 " + maternal.getSc_days() + "天";
                                } else {
                                    cfStart.setText("待产中");
                                    UserInfo.UserType = "待产中";
                                }
                            } else {
                                cfStart.setText("待产中");
                                UserInfo.UserType = "待产中";
                            }

                            cfName.setText(maternal.getName());
                            cfInfo.setText(maternal.getAge() + "岁 " + maternal.getBed_num());
                            cfInfo2.setText(maternal.getRank());
                            cfInfo2.setTextColor(Color.parseColor(maternal.getRank_color()));

                            String hospital_time = maternal.getHospital_time();
                            if (!TextUtils.isEmpty(hospital_time)) {
                                cfTime.setText(getString(R.string.admissionTime) + hospital_time.substring(0,
                                        hospital_time.indexOf(" ") != -1 ? hospital_time.indexOf(" ") : hospital_time.length()));
                            }

                            UserInfo.UserName = maternal.getName();
                            UserInfo.UserAge = maternal.getAge() + "岁";
                            UserInfo.UserTime = getString(R.string.admissionTime) + hospital_time;


                            cfZyid.setText(getString(R.string.hospitalizationID) + maternal.getHospital_id());
                            cfPhry.setText(getString(R.string.escortStaff) + maternal.getPeihu_status());
                            String zrys = "责任医生：" + maternal.getDoctor().getName();
                            String zrhs = "责任护士：" + maternal.getNurse().getName();
                            String zchs = "助产士：" + maternal.getMidwife().getName();
                            TextStyleUtils textStyleUtilszrys = new TextStyleUtils();
                            TextStyleUtils textStyleUtilszrhs = new TextStyleUtils();
                            TextStyleUtils textStyleUtilszchs = new TextStyleUtils();
                            textStyleUtilszrys.setForegroundColorSpan(cfZrys, zrys, getResources().getColor(R.color.app_theme), 0, 5);
                            textStyleUtilszrhs.setForegroundColorSpan(cfZrhs, zrhs, getResources().getColor(R.color.app_theme), 0, 5);
                            textStyleUtilszchs.setForegroundColorSpan(cfZchs, zchs, getResources().getColor(R.color.app_theme), 0, 4);
                            //底部的注意事项等
                            List<UserInfoEntity.DataBean.MaternalBean.ShowItemsBean> show_items = data.getMaternal().getShow_items();
                            if (show_items != null) {
                                showItemsBeans.clear();
                                for (UserInfoEntity.DataBean.MaternalBean.ShowItemsBean bean : data.getMaternal().getShow_items()) {
                                    if (showItemsBeans.size() < 6) {
                                        showItemsBeans.add(bean);
                                    }
                                }
                                myAdapterInfo.notifyDataSetChanged();
                            }
                            //注意事项
                            String focus_str = maternal.getFocus_str();
                            if (!TextUtils.isEmpty(focus_str)) {
                                if (focus_str.contains(" ")) {
                                    String[] s = focus_str.split(" ");
                                    if (!isHaveBroadcast) {
                                        arrayListZysx.clear();
                                        for (int i = 0; i < s.length; i++) {
                                            String s1 = s[i].trim();
                                            if (!TextUtils.isEmpty(s1)) {
                                                arrayListZysx.add((i + 1) + "、" + s1);
                                            }
                                        }

                                        if (arrayListZysx.size() > 4) {
                                            for (int i = 0; i < s.length; i++) {
                                                String s1 = s[i].trim();
                                                if (!TextUtils.isEmpty(s1)) {
                                                    arrayListZysx.add((i + 1) + "、" + s1);
                                                }
                                            }
                                        }

                                        myRecycleAdapterZysx.notifyDataSetChanged();
                                    }
                                } else {
                                    arrayListZysx.clear();
                                    arrayListZysx.add("1、" + focus_str);
                                    myRecycleAdapterZysx.notifyDataSetChanged();
                                }

                                myRecycleAdapterZysx = new MyRecycleAdapter<String>(context,
                                        arrayListZysx, R.layout.item_userknow_layout, false) {
                                    @Override
                                    protected void setPositionClick(int position) {

                                    }

                                    @Override
                                    protected void initData(MyViewHolder holder, int position) {
                                        holder.setText(R.id.userknow_tv, arrayListZysx.get(position));
                                    }
                                };
                                myRecyclerViewZYSX.setLayoutManager(new AutoScrollLayoutManager(context));
                                myRecyclerViewZYSX.setAdapter(myRecycleAdapterZysx);
                                if (arrayListZysx.size() > 0) {
                                    myRecyclerViewZYSX.smoothScrollToPosition(myRecycleAdapterZysx.getItemCount());
                                }
                            }

                            List<UserInfoEntity.DataBean.NewXibaoBean> new_xibao = data.getNew_xibao();
                            if (new_xibao.size() > 0) {
                                new_xibaos.clear();
                                new_xibaos.addAll(new_xibao);
                                showXibao(0);
                            } else {
                                // arrayListLs.clear();
                                // myAdapterInfo.setList(arrayListLs);
                                // myAdapterInfo.notifyDataSetChanged();
                            }
                            UserInfoEntity.DataBean.BabyBean baby = data.getBaby();
                            if (baby != null) {
                                shareference.saveBabyID(baby.getId() + "");
                            }
                            isHavePeople = true;
                        } else {
                            isHavePeople = false;
                        }
                        break;
                    case index_guangbo:
                        GuangBoEntity guangBoEntity = new Gson().fromJson(body, GuangBoEntity.class);
                        List<GuangBoEntity.DataBean> boEntityData = guangBoEntity.getData();
                        if (boEntityData.size() > 0) {
                            messageTitle.setText("广播通知");
                            message_iv.setVisibility(View.VISIBLE);
                            isHaveBroadcast = true;

                            arrayListZysx.clear();
                            boEntitys.clear();
                            for (int i = 0; i < boEntityData.size(); i++) {
                                GuangBoEntity.DataBean dataBean = boEntityData.get(i);
                                if (dataBean.getVideofile().contains(".mp3") || dataBean.getVideofile().contains(".mp4")) {
                                    boEntitys.add(dataBean);
                                    arrayListZysx.add(dataBean.getContent());
                                } else {
                                    arrayListZysx.add(dataBean.getContent());
                                }
                            }
                            if (boEntitys.size() > 0) {
                                startMusic(0);
                            }
                            myRecycleAdapterZysx.notifyDataSetChanged();
                        } else {
                            messageTitle.setText(getString(R.string.pointsAttention));
                            message_iv.setVisibility(View.GONE);
                            isHaveBroadcast = false;
                            myRecycleAdapterZysx.notifyDataSetChanged();
                        }

                        break;
                    case index_zan:
                        shareference.saveXiBaoData(xibaoID, true);

                        JSONObject object = new JSONObject(body);
                        if (object.getInt("code") == 1) {
                            int i = Integer.valueOf(zan) + 1;
                            cfDianzan.setText(i + "人祝贺");
                        }

                        break;
                    case index_doctor:
                        JSONObject jsonObject = new JSONObject(body);
                        String doctor = jsonObject.getString("doctor");
                        String nurse = jsonObject.getString("nurse");

                        String zbts = "值班医生：" + doctor;
                        String zbhs = "值班护士：" + nurse;

                        TextStyleUtils textStyleUtilszbts = new TextStyleUtils();
                        TextStyleUtils textStyleUtilszbhs = new TextStyleUtils();
                        textStyleUtilszbts.setForegroundColorSpan(cfZbys, zbts, getResources().getColor(R.color.app_theme), 0, 5);
                        textStyleUtilszbhs.setForegroundColorSpan(cfZbhs, zbhs, getResources().getColor(R.color.app_theme), 0, 5);

                        break;
                    case index_bedinfo:
                        smartHomeEntity = new Gson().fromJson(body, SmartHomeEntity.class);
                        LogUtils.e("智能:" + body);
                        intelligentDataBeanList.clear();
                        SmartHomeEntity.DataBean homeEntityData = smartHomeEntity.getData();
                        if (homeEntityData != null) {
                            if (homeEntityData.getIntelligent_data() != null) {
                                for (SmartHomeEntity.DataBean.IntelligentDataBean bean : homeEntityData.getIntelligent_data()) {
                                    intelligentDataBeanList.add(bean);
                                    if (bean.getInfo().getName().equals("灯光控制")) {

                                    }
                                    int[] ints = new int[9];
                                    for (int i = 0; i < ints.length; i++) {
                                        ints[i] = 0;
                                    }
                                    dataList.add(ints);
                                }
                            }
                            initRyZnjjAdapter();
//                        smartHomeAdapter = new SmartHomeAdapter(this, intelligentDataBeanList);
                            myRecyclerZnjj.setAdapter(myRecycleAdapterZn);
                        }

                        break;
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    String lastText = "";
    long lastTime = 0;
    CountDownTimer mSpeechTextTimer;

    private void speechText(String text) {
        Log.e("speechText", "speechText:" + text);
        long time = System.currentTimeMillis();
        if (isBusy || (lastText.equals(text) && time - lastTime < 1000 * 5)) {//通话中 或者间隔不到5秒 或者重复播音  都忽略
            Log.e("speechText", "---ignore speechText:" + text);
            return;
        }
        lastTime = time;
        lastText = text;
        chineseToSpeech.speech(text);
        if (inComingCall) {
            lastText = "";
            lastTime = 0;
            isBusy = false;
            if (mSpeechTextTimer != null) {
                mSpeechTextTimer.cancel();
            }
            mSpeechTextTimer = new CountDownTimer(10 * 1000, 1000) {
                @Override
                public void onTick(long millisUntilFinished) {

                }

                @Override
                public void onFinish() {
                    if (inComingCall) {
                        speechText("护士端呼叫...");
                    }
                }
            }.start();
        }
    }

    List<UserInfoEntity.DataBean.NewXibaoBean> new_xibaos = new ArrayList<>();
    CountDownTimer mShowBannerTimer;

    private void showXibao(int index) {
        UserInfoEntity.DataBean.NewXibaoBean newXibaoBean = new_xibaos.get(index);
        String image = newXibaoBean.getImages();
        ArrayList<String> bannerList = new ArrayList<String>();
        if (image.contains(",")) {
            String[] split = image.split(",");
            for (int i = 0; i < split.length; i++) {
                String s = split[i];
                if (!TextUtils.isEmpty(s)) {
                    bannerList.add(imageUrl + s);
                }
            }
        } else {
            bannerList.add(imageUrl + image);
        }
        Log.e("imgs", new Gson().toJson(bannerList));
        banner.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int position) {

            }
        });

        banner.setImages(bannerList).setImageLoader(new ImageLoader() {
            @Override
            public void displayImage(Context context, Object path, ImageView imageView) {
                Log.e("tag", "img:" + path);
                try {
                    Picasso.with(context).load((String) path).error(R.drawable.iv_baby_def).into(imageView);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).setDelayTime(5000).start();
        xibaoID = newXibaoBean.getId();
        Log.e("xiBaoDataId", "xibaoID==>" + xibaoID);
        if (shareference.getXiBaoDataZt(xibaoID)) {
            dianxin.setImageDrawable(getResources().getDrawable(R.drawable.iv_dianxin_y));
            dianxin.setEnabled(false);
        } else {
            dianxin.setImageDrawable(getResources().getDrawable(R.drawable.iv_dianxin_n));
            dianxin.setEnabled(true);
        }
        cfXbmr.setText(newXibaoBean.getContent());
        String birthday = newXibaoBean.getBirthday();
        cfCsrq.setText("出生时间：" + birthday);
        zan = newXibaoBean.getZan();
        if (TextUtils.isEmpty(zan)) {
            cfDianzan.setText("0人祝贺");
        } else {
            cfDianzan.setText(zan + "人祝贺");
        }

        Log.e("xibao", "show:" + index);
        try {
            if (mShowBannerTimer != null) {
                mShowBannerTimer.cancel();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        mShowBannerTimer = new CountDownTimer(60 * 1000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                //Log.e("xibao", "onTick:" + millisUntilFinished);
            }

            @Override
            public void onFinish() {
                try {
                    int index2 = index + 1;
                    if (index2 < new_xibaos.size()) {
                        showXibao(index2);
                    } else {
                        index2 = 0;
                        showXibao(index2);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();

    }


    @Override
    public void requestCurrencyViewFailed(int type, int code) {
        switch (type) {
//            case index_check_call_status:
//                showToast("通话状态有误");
//                user_input_view.setVisibility(View.VISIBLE);
//                calling_view.setVisibility(View.GONE);
//                break;
            case index_addcalllog:
                showToast("呼叫记录提交失败");
                user_input_view.setVisibility(View.VISIBLE);
                calling_view.setVisibility(View.GONE);
                break;
            case index_index:
                isHavePeople = false;
                email = "";
                shareference.saveUserID("");
                enter_manage.setImageResource(R.drawable.iv_tx);
                cfStart.setText(getString(R.string.isnullpeople));
                UserInfo.UserType = getString(R.string.isnullpeople);
                cfStartbg.setBackgroundResource(R.color.green);
                cfStart.setTextColor(getResources().getColor(R.color.green));
                cfName.setText(getString(R.string.isnullpeople));
                cfInfo.setText(shareference.getBedName() + "");
                cfTime.setText(getString(R.string.isnullpeople));
                UserInfo.UserName = getString(R.string.isnullpeople);
                UserInfo.UserAge = getString(R.string.isnullpeople);
                UserInfo.UserTime = getString(R.string.isnullpeople);
                cfZyid.setText(getString(R.string.isnullpeople));
                cfPhry.setText(getString(R.string.isnullpeople));

                String zrys = "责任医生：";
                String zrhs = "责任护士：";
                String zchs = "助产士：";
                TextStyleUtils textStyleUtilszrys = new TextStyleUtils();
                TextStyleUtils textStyleUtilszrhs = new TextStyleUtils();
                TextStyleUtils textStyleUtilszchs = new TextStyleUtils();
                textStyleUtilszrys.setForegroundColorSpan(cfZrys, zrys, getResources().getColor(R.color.app_theme), 0, 5);
                textStyleUtilszrhs.setForegroundColorSpan(cfZrhs, zrhs, getResources().getColor(R.color.app_theme), 0, 5);
                textStyleUtilszchs.setForegroundColorSpan(cfZchs, zchs, getResources().getColor(R.color.app_theme), 0, 4);
                showItemsBeans.clear();
                myAdapterInfo.notifyDataSetChanged();
                arrayListZysx.clear();
                myRecycleAdapterZysx.notifyDataSetChanged();
                dianxin.setImageDrawable(getResources().getDrawable(R.drawable.iv_dianxin_n));
                shareference.saveBabyID("-1");
                break;


        }

    }

    /**
     * 产妇信息 /api/index/index
     */
    private final int index_index = 1;

    private void requestImfoIndex() {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("house_id", shareference.getUserHouseID()); //	房间id  21
        hashMap.put("bed_id", shareference.getUserBedID());//   	床位id  11
        if (utilsManage.isNull(hashMap)) {
            //  showToast(getString(R.string.message_isnull));
        } else {
            getP().requestGet(index_index, UrlManage.APP_URL + "index/index", hashMap);
        }
    }

    /**
     * 广播 /api/index/guangbo
     */
    private final int index_guangbo = 2;

    private void requestGuangboIndex() {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("person", "2");
        if (utilsManage.isNull(hashMap)) {

        } else {
//            getP().requestGet(index_guangbo, urlManage.APP_URL + "index/guangbo", hashMap);
            getP().requestGet(index_guangbo, urlManage.APP_URL + "index/broadcast", hashMap);
        }
    }

    /**
     * 点赞 /api/index/zan
     */
    private final int index_zan = 3;

    private void submitZan() {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("xibao_id", xibaoID);
        getP().requestGet(index_zan, urlManage.APP_URL + "index/zan", hashMap);
    }

    /**
     * 值班医生 /api/doctor/doctor
     */
    private final int index_doctor = 4;

    private void requestDoctor() {

        HashMap<String, String> map = new HashMap<>();
        map.put("maternal_id", shareference.getUserID());
        getP().requestGet(index_doctor, UrlManage.APP_URL + "doctor/doctor", map);
    }

    /**
     * 保存呼叫记录 /api/index/addcalllog
     */
    private final int index_addcalllog = 5;

    /**
     * 智能家居 /api/index/bedinfo
     */
    private final int index_bedinfo = 6;

    private void requestBedinfo() {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("bed_id", shareference.getUserBedID());
        getP().requestGet(index_bedinfo, urlManage.APP_URL + "index/bedinfo", hashMap);
        //    getP().requestGet(index_bedinfo, "http://baby.myloveqd.com/api/index/bedinfo?house_id=14&bed_id=4");
    }


    private void stopLoadCallLogTimer() {
        if (loadCallLogTimer != null) {
            loadCallLogTimer.cancel();
        }
    }

    CountDownTimer loadCallLogTimer = null;

    private void startLoadCallLogTimer() {
        if (loadCallLogTimer != null) {
            loadCallLogTimer.cancel();
        }
        new CountDownTimer(1000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                Log.d("ddd", "onTick");
            }

            @Override
            public void onFinish() {
                loadCallLogs();
            }
        }.start();
    }

    private void loadCallLogs() {
        HashMap<String, String> map = new HashMap<>();
        map.put("no", this.shareference.getLinPhonDataZh());
        map.put("call_status", "");
        getP().requestPost(type_load_calllogs, UrlManage.APP_URL + "doctor/newcalllist", map);
    }

    private int ClockStstus=0;//在时钟界面是1，不在是0
    public void initLinPhoneCall() {

        LinphoneService.removeAllCallback();
        String linPhonDataIp = shareference.getLinPhonDataIp();
        String linPhonDataDq = shareference.getLinPhonDataDq();
        String linPhonDataZh = shareference.getLinPhonDataZh();
        String linPhonDataMm = shareference.getLinPhonDataMm();
        PhoneCallback phoneCallback = new PhoneCallback() {
            @Override
            public void incomingCall(LinphoneCall linphoneCall) {
                // 来电状态
                super.incomingCall(linphoneCall);
                FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();

                if (view_clack_black.getVisibility()==View.VISIBLE){
                    view_clack_black.setVisibility(View.GONE);
                    setBtnClick(btn_main);
                }
                if (view_front_black.getVisibility()==View.VISIBLE){
                    view_front_black.setVisibility(View.GONE);
                    setBtnClick(btn_main);
                }

                if (main_cardv.getVisibility()==View.VISIBLE){
                    main_cardv.setVisibility(View.GONE);
                    setBtnClick(btn_main);
                }

                EasyLinphone.toggleSpeaker(true);
                targetidText.setText("来电中...");
                inComingCall = true;
                speechText("护士端呼叫...");
                mCallIn.setVisibility(View.VISIBLE);
                mHangUp.setVisibility(View.VISIBLE);
                user_input_view.setVisibility(View.GONE);
                calling_view.setVisibility(View.VISIBLE);
                if (controlView.getVisibility() == View.VISIBLE) {
                    controlView.setVisibility(View.GONE);
                    root_view.setVisibility(View.VISIBLE);
                }
                isCallPhone = true;
//                isAnswer = true;
                isBusy = false;
                startLoadCallLogTimer();
                //点亮屏幕
                view_front_black.setVisibility(View.GONE);
                setDelayTimeToScreen();
            }

            @Override
            public void outgoingInit(LinphoneCall linphoneCall) {
                // 呼叫初始化
                super.outgoingInit(linphoneCall);
//                    chineseToSpeech.speech("正在呼叫...");
                inComingCall = false;
                targetidText.setText("呼叫中...");
                speechText("正在呼叫...");
                mHangUp.setVisibility(View.VISIBLE);
                user_input_view.setVisibility(View.GONE);
                calling_view.setVisibility(View.VISIBLE);
                if (controlView.getVisibility() == View.VISIBLE) {
                    controlView.setVisibility(View.GONE);
                    root_view.setVisibility(View.VISIBLE);
                }

                isCallPhone = true;
//                isAnswer = false;
                isBusy = true;
                view_front_black.setVisibility(View.GONE);
                setDelayTimeToScreen();
            }

            @Override
            public void callConnected(LinphoneCall linphoneCall) {
                // 电话接通
                super.callConnected(linphoneCall);
                inComingCall = false;
                // 视频通话默认免提，语音通话默认非免提
                EasyLinphone.toggleSpeaker(EasyLinphone.getVideoEnabled());
                // 所有通话默认非静音
                EasyLinphone.toggleMicro(false);
                mCallIn.setVisibility(View.GONE);
                mHangUp.setVisibility(View.VISIBLE);
                mToggleSpeaker.setVisibility(View.VISIBLE);
                mToggleMute.setVisibility(View.VISIBLE);
                mToggleMute.setVisibility(View.VISIBLE);
                targetidText.setText("通话中...");
                speechText("已接通...");
                user_input_view.setVisibility(View.GONE);
                calling_view.setVisibility(View.VISIBLE);
                isBusy = true;
                isCallPhone = true;
            }

            @Override
            public void paused(LinphoneCall linphoneCall) {
                super.paused(linphoneCall);
                inComingCall = false;
                mCallIn.setVisibility(View.GONE);
                mHangUp.setVisibility(View.VISIBLE);
                mToggleSpeaker.setVisibility(View.VISIBLE);
                mToggleMute.setVisibility(View.VISIBLE);
                targetidText.setText("暂停通话...");
                speechText("暂停通话...");
                user_input_view.setVisibility(View.GONE);
                calling_view.setVisibility(View.VISIBLE);
                isBusy = true;
                isCallPhone = true;
            }

            @Override
            public void Resuming(LinphoneCall linphoneCall) {
                super.Resuming(linphoneCall);
                inComingCall = false;
                mCallIn.setVisibility(View.GONE);
                mHangUp.setVisibility(View.VISIBLE);
                mToggleSpeaker.setVisibility(View.VISIBLE);
                mToggleMute.setVisibility(View.VISIBLE);
                targetidText.setText("通话中...");
                speechText("恢复通话...");
                user_input_view.setVisibility(View.GONE);
                calling_view.setVisibility(View.VISIBLE);
                isBusy = true;
                isCallPhone = true;
            }

            @Override
            public void callEnd(LinphoneCall linphoneCall) {
                // 电话挂断
                super.callEnd(linphoneCall);
                if(localTag==5){
                    view_clack_black.setVisibility(View.VISIBLE);
                }
                else if (localTag==6){
                    view_front_black.setVisibility(View.VISIBLE);
                }
                inComingCall = false;
                speechText("结束通话...");
//                if (isAnswer) {
//                } else {
//                    speechText("取消呼叫...");
//                }

                user_input_view.setVisibility(View.VISIBLE);
                calling_view.setVisibility(View.GONE);
                mCallIn.setVisibility(View.GONE);
                mHangUp.setVisibility(View.VISIBLE);
                mToggleMute.setVisibility(View.INVISIBLE);
                mToggleSpeaker.setVisibility(View.INVISIBLE);
                targetidText.setText("结束通话...");
                Log.e("linphone", "callEnd" + linphoneCall);
                isBusy = false;
                isCallPhone = false;
            }

            @Override
            public void error() {
                super.error();
                speechText("通话异常,请重试...");
                user_input_view.setVisibility(View.VISIBLE);
                calling_view.setVisibility(View.GONE);
                mCallIn.setVisibility(View.GONE);
                mHangUp.setVisibility(View.VISIBLE);
                mToggleMute.setVisibility(View.INVISIBLE);
                mToggleSpeaker.setVisibility(View.INVISIBLE);
                targetidText.setText("异常结束...");
                Log.e("linphone", "error");
                isBusy = false;
                isCallPhone = false;
            }

            @Override
            public void callReleased(LinphoneCall linphoneCall) {
                super.callReleased(linphoneCall);
                // 电话挂断
                super.callEnd(linphoneCall);
                if (isBusy) {
                    speechText("结束通话...");
                }
                user_input_view.setVisibility(View.VISIBLE);
                calling_view.setVisibility(View.GONE);
                mCallIn.setVisibility(View.GONE);
                mHangUp.setVisibility(View.VISIBLE);
                mToggleMute.setVisibility(View.INVISIBLE);
                mToggleSpeaker.setVisibility(View.INVISIBLE);
                targetidText.setText("结束通话...");
                Log.e("linphone", "callEnd" + linphoneCall);
                isBusy = false;
                isCallPhone = false;
            }
        };
        EasyLinphone.addCallback(new RegistrationCallback() {
            @Override
            public void registrationOk() {
                super.registrationOk();
                LoadDialog.dismiss(context);
                showToast("登录成功！");
            }

            @Override
            public void registrationFailed() {
                LoadDialog.dismiss(context);
                super.registrationFailed();
                showToast("登录失败！");
            }

            @Override
            public void registrationProgress() {
                super.registrationProgress();
                LoadDialog.show(context, "登录中");
            }

            @Override
            public void registrationNone() {
                super.registrationNone();
            }

            @Override
            public void registrationCleared() {
                super.registrationCleared();
            }
        }, phoneCallback);

        if (TextUtils.isEmpty(linPhonDataIp) || TextUtils.isEmpty(linPhonDataDq) ||
                TextUtils.isEmpty(linPhonDataZh) || TextUtils.isEmpty(linPhonDataMm)) {
            startActivity(new Intent(context, ControllerActivity.class));
        } else {
            EasyLinphone.setAccount(linPhonDataZh, linPhonDataMm, linPhonDataIp + ":" + "5060");
            EasyLinphone.login();
        }
    }

    //语音呼叫//接听状态１接通２未接通3拒接4呼叫保持5取消呼叫
    public void audioCall(String dialNum) {
        isUpDateStatus = false;
        String bindNurseAccount = shareference.getBindNurseUser();
        if (!TextUtils.isEmpty(bindNurseAccount)) {
            phoneNumber = bindNurseAccount;
        }
        if (TextUtils.isEmpty(phoneNumber) || !isHavePeople) {
            showToast("未获取到责任人，请联系医护人员");
            speechText("未获取到责任人,请稍后重试，或联系医护人员");
            requestImfoIndex();
            return;
        }
//        if (isHavePeople) {
        EasyLinphone.callTo(dialNum, false);
        try {
            user_input_view.setVisibility(View.GONE);
            calling_view.setVisibility(View.VISIBLE);
            targetidText.setText("呼叫中...");
        } catch (Exception e) {
            e.printStackTrace();
        }

        String zrhs = "";//责任护士
        String zrhs_id = "";//责任护士id
        try {
            String hospital_id = maternalData.getMaternal().getHospital_id();//住院号
            String peiHuStatus = maternalData.getMaternal().getPeihu_status();//陪护状态
            String zrys = maternalData.getMaternal().getDoctor().getName();//责任医生
            zrhs = maternalData.getMaternal().getNurse().getName();
            zrhs_id = maternalData.getMaternal().getNurse().getId();
            String zchs = maternalData.getMaternal().getMidwife().getName();//助产士
        } catch (Exception e) {
            e.printStackTrace();
        }

        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("maternal_id", shareference.getUserID());
        String doctor = zrhs_id;//护士id
        hashMap.put("doctor", doctor);
        hashMap.put("callname", UserInfo.UserName);
        hashMap.put("answername", zrhs);
        hashMap.put("from", shareference.getLinPhonDataZh());
        hashMap.put("to", dialNum);
        hashMap.put("call_status", "2");//未接听
        hashMap.put("calltime", TimeUtil.getTimeString());
        getP().requestGet(index_addcalllog, UrlManage.APP_URL + "index/addcalllog", hashMap);

//        }
        isCallPhone = true;
        //checkCallingStatus();
    }


//    private void checkCallingStatus() {
//        new CountDownTimer(1000, 1000) {
//            @Override
//            public void onTick(long millisUntilFinished) {
//
//            }
//
//            @Override
//            public void onFinish() {
//                if (!TextUtils.isEmpty(callingLogId)) {
//                    HashMap<String, String> hashMap = new HashMap<>();
//                    hashMap.put("id", callingLogId);
//                    getP().requestGet(index_check_call_status, urlManage.APP_URL + "/index/calldetail", hashMap);
//                    checkCallingStatus();
//                }
//            }
//        }.start();
//    }

    // 点击接听
    public void acceptCall() {
        changeCallStatus("1");
        EasyLinphone.acceptCall();
        isUpDateStatus = false;
    }

    // 挂断
    public void hangUp() {
        if (isUpDateStatus) {
            changeCallStatus("3");
        } else {
//            changeCallStatus("5");
        }
        EasyLinphone.hangUp();
        isBusy = false;
        isCallPhone = false;
        isUpDateStatus = true;
    }

    private void changeCallStatus(String status) {
        if (TextUtils.isEmpty(callingLogId)) {
            Log.d("callingLogId", "callingLogId:" + callingLogId);
            return;
        }
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("id", callingLogId);
        hashMap.put("call_status", status);
        getP().requestGet(index_change_call_status, UrlManage.APP_URL + "/doctor/editcall", hashMap);
    }

    //切换静音
    public void toggleMute() {
        EasyLinphone.toggleMicro(!EasyLinphone.getLC().isMicMuted());
    }

    //切换免提
    public void toggleSpeaker() {
        EasyLinphone.toggleSpeaker(!EasyLinphone.getLC().isSpeakerEnabled());
    }

//    @Override
//    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        if (keyCode == KeyEvent.KEYCODE_BACK) {
//            Intent intent = new Intent(Intent.ACTION_MAIN);
//            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//            intent.addCategory(Intent.CATEGORY_HOME);
//            startActivity(intent);
//            return true;
//        }
//        return super.onKeyDown(keyCode, event);
//    }

    private void initRyZnjjAdapter() {
        myRecycleAdapterZn = new MyRecycleAdapter<SmartHomeEntity.DataBean.IntelligentDataBean>(
                context, intelligentDataBeanList, R.layout.layout_smart_znjj, false) {

            ImageView smart_dg_iv;
            View dengguang, dengguangly;
            NumberSeekBar NumberSeekBar1, NumberSeekBar2, NumberSeekBar3;

            @Override
            protected void setPositionClick(int position) {

            }

            @Override
            protected void initData(MyViewHolder holder, final int position) {
                final SmartHomeEntity.DataBean.IntelligentDataBean intelligentDataBean = intelligentDataBeanList.get(position);
                final SmartHomeEntity.DataBean.IntelligentDataBean.InfoBean info = intelligentDataBean.getInfo();
                String name = intelligentDataBean.getInfo().getName();

                holder.setVisibile(R.id.layout_smart_kt, false);
                holder.setVisibile(R.id.layout_smart_cl, false);
                holder.setVisibile(R.id.layout_smart_wl, false);
                holder.setVisibile(R.id.layout_smart_ds, false);
                holder.setVisibile(R.id.layout_smart_dg, false);
                holder.setVisibile(R.id.layout_smart_xf, false);

                if (name.equals("智能空调")) {
                    holder.setVisibile(R.id.layout_smart_kt, true);
                } else if (name.equals("智能窗帘")) {
                    holder.setVisibile(R.id.layout_smart_cl, true);

                    View open_cl = holder.getView(R.id.open_cl);
                    View close_cl = holder.getView(R.id.close_cl);
                    View stop_cl = holder.getView(R.id.stop_cl);

                    open_cl.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            String address = intelligentDataBean.getAddress();
                            String commd = "";
                            if (intelligentDataBean.getInfo() != null && intelligentDataBean.getInfo().getExtend() != null) {
                                commd = intelligentDataBean.getInfo().getExtend().get(0).getCommand();
                                modbusMaster.addModbusToEendData(address + commd);
                            }
                        }
                    });
                    close_cl.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            String address = intelligentDataBean.getAddress();
                            String commd = "";
                            if (intelligentDataBean.getInfo() != null && intelligentDataBean.getInfo().getExtend() != null) {
                                commd = intelligentDataBean.getInfo().getExtend().get(2).getCommand();
                                modbusMaster.addModbusToEendData(address + commd);
                            }
                        }
                    });
                    stop_cl.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            String address = intelligentDataBean.getAddress();
                            String commd = "";
                            if (intelligentDataBean.getInfo() != null && intelligentDataBean.getInfo().getExtend() != null) {
                                commd = intelligentDataBean.getInfo().getExtend().get(1).getCommand();
                                modbusMaster.addModbusToEendData(address + commd);
                            }
                        }
                    });

                } else if (name.equals("智能围帘")) {
                    holder.setVisibile(R.id.layout_smart_wl, true);

                    View open_wl = holder.getView(R.id.open_wl);
                    View close_wl = holder.getView(R.id.close_wl);
                    View stop_wl = holder.getView(R.id.stop_wl);

                    open_wl.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            String address = intelligentDataBean.getAddress();
                            String commd = "";
                            if (intelligentDataBean.getInfo() != null && intelligentDataBean.getInfo().getExtend() != null) {
                                commd = intelligentDataBean.getInfo().getExtend().get(0).getCommand();
                                modbusMaster.addModbusToEendData(address + commd);
                            }
                        }
                    });
                    close_wl.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            String address = intelligentDataBean.getAddress();
                            String commd = "";
                            if (intelligentDataBean.getInfo() != null && intelligentDataBean.getInfo().getExtend() != null) {
                                commd = intelligentDataBean.getInfo().getExtend().get(2).getCommand();
                                modbusMaster.addModbusToEendData(address + commd);
                            }
                        }
                    });
                    stop_wl.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            String address = intelligentDataBean.getAddress();
                            String commd = "";
                            if (intelligentDataBean.getInfo() != null && intelligentDataBean.getInfo().getExtend() != null) {
                                commd = intelligentDataBean.getInfo().getExtend().get(1).getCommand();
                                modbusMaster.addModbusToEendData(address + commd);
                            }
                        }
                    });

                } else if (name.equals("智能电视")) {
                    holder.setVisibile(R.id.layout_smart_ds, true);
                } else if (name.equals("新风控制")) {
                    holder.setVisibile(R.id.layout_smart_xf, true);
                } else {
                    holder.setVisibile(R.id.layout_smart_dg, true);

                    smart_dg_iv = holder.getView(R.id.smart_dg_iv);
                    dengguang = holder.getView(R.id.dengguang);
                    dengguangly = holder.getView(R.id.dengguangly);
                    NumberSeekBar1 = holder.getView(R.id.NumberSeekBar1);
                    NumberSeekBar2 = holder.getView(R.id.NumberSeekBar2);
                    NumberSeekBar3 = holder.getView(R.id.NumberSeekBar3);

                    if (info.getMode().contains("普通")) {
                        dengguangly.setVisibility(View.GONE);
                    } else {
                        dengguangly.setVisibility(View.VISIBLE);
                        if (info.getMode().equals("色彩")) {
                            smart_dg_iv.setVisibility(View.VISIBLE);
                        } else {
                            smart_dg_iv.setVisibility(View.GONE);
                        }
                    }

                    dengguang.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            String dataBeanAddress = intelligentDataBean.getAddress();
                            address = Integer.valueOf(dataBeanAddress);
                            anInt = position;
                            int[] ints = dataList.get(anInt);
                            for (int i = 0; i < ints.length; i++) {
                                ints[i] = 0;
                            }
                            setMasterAddress();
                        }
                    });
                    smart_dg_iv.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            String dataBeanAddress = intelligentDataBean.getAddress();
                            address = Integer.valueOf(dataBeanAddress);
                            anInt = position;
                            showColorPickerView();
                        }
                    });
                    NumberSeekBar1.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                        @Override
                        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                            Log.e("progress", "progress" + progress);
                            String dataBeanAddress = intelligentDataBean.getAddress();
                            address = Integer.valueOf(dataBeanAddress);
                            anInt = position;
                            int[] data = dataList.get(anInt);
                            switch (info.getMode()) {
                                case "色彩":
                                    data[4] = progress * 2;//冷色:0-255
                                    data[6] = progress * 10;//冷色dac:0-1000
                                    data[8] = progress * 10;//冷色pwm:0-1000
                                    setMasterAddress();
                                    break;
                                case "色温":
                                    setTwoColor(false, progress, 0);
                                    break;
                            }
                        }

                        @Override
                        public void onStartTrackingTouch(SeekBar seekBar) {

                        }

                        @Override
                        public void onStopTrackingTouch(SeekBar seekBar) {

                        }
                    });
                    NumberSeekBar2.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                        @Override
                        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                            Log.e("progress", "progress" + progress);
                            String dataBeanAddress = intelligentDataBean.getAddress();
                            address = Integer.valueOf(dataBeanAddress);
                            anInt = position;
                            int[] data = dataList.get(anInt);
                            switch (info.getMode()) {
                                case "色彩":
                                    data[3] = progress * 2;//暖色:0-255
                                    data[5] = progress * 10;//暖色dac:0-1000
                                    data[7] = progress * 10;//暖色pwm:0-1000
                                    setMasterAddress();
                                    break;
                                case "色温":
                                    setTwoColor(true, 0, progress);
                                    break;
                            }
                        }

                        @Override
                        public void onStartTrackingTouch(SeekBar seekBar) {

                        }

                        @Override
                        public void onStopTrackingTouch(SeekBar seekBar) {

                        }
                    });
                    NumberSeekBar3.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                        @Override
                        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                            Log.e("progress", "progress" + progress);
                            String dataBeanAddress = intelligentDataBean.getAddress();
                            address = Integer.valueOf(dataBeanAddress);
                            anInt = position;
                            setDanse(progress);
                        }

                        @Override
                        public void onStartTrackingTouch(SeekBar seekBar) {

                        }

                        @Override
                        public void onStopTrackingTouch(SeekBar seekBar) {

                        }
                    });
                }
            }
        };
    }

    private ColorPickerView colorDisk = null;
    private TextView tv = null;
    List<int[]> dataList = new ArrayList();

    private void showColorPickerView() {
        View inflate = LayoutInflater.from(context).inflate(R.layout.activity_lighting, null);
        utilsManage.dialog(this, inflate, Gravity.BOTTOM, true);

        colorDisk = inflate.findViewById(R.id.colorDisk);
        tv = inflate.findViewById(R.id.tv);

        colorDisk.setOnColorBackListener(new ColorPickerView.OnColorBackListener() {
            @Override
            public void onColorBack(int a, int r, int g, int b) {
                tv.setText("R：" + r + "\nG：" + g + "\nB：" + b + "\n" + colorDisk.getColorStr());
                tv.setTextColor(Color.argb(a, r, g, b));

                /**
                 * 定义数组共5位
                 * 彩色灯光
                 */
                int[] data = dataList.get(anInt);
                data[0] = r / 3;//红色
                data[1] = g / 3;//绿色
                data[2] = b / 3;//蓝色
                data[3] = 0;//暖色:0-255
                data[4] = 0;//冷色:0-255
                data[5] = 0;//暖色dac:0-1000
                data[6] = 0;//冷色dac:0-1000
                data[7] = 0;//暖色pwm:0-1000
                data[8] = 0;//冷色pwm:0-1000
                /**
                 * 发送地址为0x01
                 * 固定位0x10
                 * 起始位为0
                 * data数据
                 */
                setMasterAddress();
            }
        });
    }

    private void setDanse(int progress) {
        int[] data = dataList.get(anInt);
        data[0] = 0;//红色
        data[1] = 0;//绿色
        data[2] = 0;//蓝色
        data[3] = progress * 2;//暖色:0-255
        data[4] = progress * 2;//冷色:0-255

        data[5] = progress * 10;//暖色dac:0-1000
        data[6] = progress * 10;//冷色dac:0-1000
        data[7] = progress * 10;//暖色pwm:0-1000
        data[8] = progress * 10;//冷色pwm:0-1000
        setMasterAddress();
    }

    private void setTwoColor(boolean type, int progress1, int progress2) {
        int[] data = dataList.get(anInt);
        data[0] = 0;//红色
        data[1] = 0;//绿色
        data[2] = 0;//蓝色
        if (type) {
            data[3] = progress2 * 2;//暖色:0-255
            data[5] = progress2 * 10;//暖色dac:0-1000
            data[7] = progress2 * 10;//暖色pwm:0-1000
        } else {
            data[4] = progress1 * 2;//冷色:0-255
            data[6] = progress1 * 10;//冷色dac:0-1000
            data[8] = progress1 * 10;//冷色pwm:0-1000
        }
        setMasterAddress();
    }

    private void setMasterAddress() {
        int[] data = dataList.get(anInt);
        Log.e("sssssssss", "address" + address + "data" + ((byte) DataToolsUtils.dizhi[address]));
        for (int i = 0; i < data.length; i++) {
            Log.e("sssssssss", data[i] + "");
        }
        modbusMaster.sendDataMaster((byte) DataToolsUtils.dizhi[address], (byte) 0x10, 0, data);
    }


}